﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ComLib.ComType;
using ComLib.ComFun;
using System.IO;
using ComLib.ConfigService;
using ProcessConfig.ConfigType;
using ProcessConfig;
using PixelDetectSDKInterface;
using LogLib;
using _FGDetectAssessProfile = PixelDetectSDKInterface._FGDetectAssessProfile;
using _FGDetectAssess = PixelDetectSDKInterface._FGDetectAssess;

namespace DetectProcessing
{
    public class AssessProcess
    {
         /// <summary>
        /// 像素检测句柄
        /// </summary>
        protected IntPtr _handler = IntPtr.Zero;
        public IntPtr Handler
        {
            set { _handler = value; }
            get { return _handler; }
        }

        /// <summary>
        /// 评价略略选项
        /// </summary>
        //private DetectAssessPolicies _policies = new DetectAssessPolicies();
        //public DetectAssessPolicies AssessPolicies
        //{
        //    get { return _policies; }
        //    set { _policies = value; }
        //}

        //protected bool _bApplyAssessProfile = false;

        protected byte[] _byteImage = null;

        protected _FGDetectAssess _detectAssess = new _FGDetectAssess();

        protected _FGDetectAssessProfile _profile = new _FGDetectAssessProfile();

        /// <summary>
        /// 错误信息
        /// </summary>
        protected string _error = "";
        public string ErrorMessage
        {
            get { return _error; }
            set { _error = value; }
        }

        public AssessProcess(IntPtr hDetect, DetectAssessPolicies policies)
        {
            _handler = hDetect;
            //_policies = policies;
            InitFGDetectAssessProfile();
        }

        public void InitFGDetectAssessProfile()
        {
            //_bApplyAssessProfile = true;
    
        }

        public void DetectAssess(RecogOut detecRes)
        {
            _error = "";
            Action<string, string> OnDetectFailedHandler = (strInfo, errorInfo) =>
            {
                detecRes.UnAcceptItem = UnAcceptableItem.GetDetectAccess;
                _error = detecRes.Correction.Tips = strInfo + errorInfo;
                Log.WriteAsync(detecRes.Correction.Tips);
            };

            _byteImage = IPCCom.ReadByteArray(detecRes.DestImagePath);
            if (_byteImage == null || _byteImage.Length == 0)          
            {
                OnDetectFailedHandler("检测时获取图像数据失败: ", "-99");
                Log.WriteAsync(_error);
                return;
            }

            int ret = DetectSDKInterface.LoadImage(_handler, _byteImage, _byteImage.Length);
            if (0 != ret)
            {
                OnDetectFailedHandler("检测时加载LoadImage失败: ", DetectHandleResult.ParseErrorMessage(ret));
                Log.WriteAsync(_error);
                return;
            }
            ret = DetectSDKInterface.DetectImage(_handler);
            if (0 != ret)
            {
                OnDetectFailedHandler("检测时加载DetectImage失败: ", DetectHandleResult.ParseErrorMessage(ret));
                Log.WriteAsync(_error);
                return;
            }
            ret = PixelDetectSDK.Assess(_handler, out _detectAssess); //检测并获取图像品质          
            if (ret != 0)
            {
                _byteImage = null;
                OnDetectFailedHandler("获取检测结果评价失败: ", DetectHandleResult.ParseErrorMessage(ret));
                Log.WriteAsync(_error);
                return;
            }          
            _byteImage = null;
            if(_detectAssess.pass > 0)
            {
                detecRes.PassElems.PxlQcPass = true;
            }
            else
            {
                detecRes.PassElems.PxlQcPass = false;
                GetAssessedTips(detecRes);
            }
        }

        protected void OnApplyAssessProfile(RecogOut detecRes)
        {
            //Log.WriteAsync("开始执行应用评价策略...");
            //int ret = PxlDetect.FGDetectAssessApplyProfile(ref _detectAssess, ref _profile);
            //if (ret != 0)
            //{
            //    detecRes.Correction.Tips = "应用评价策略失败, " + ret.ToString();
            //    Log.WriteAsync(detecRes.Correction.Tips);
            //    detecRes.PassElems.PxlQcPass = false;
            //    detecRes.UnAcceptItem = UnAcceptableItem.PxlAssessApplyProfile;
            //    detecRes.Correction.Tips = "应用评价策略失败";
            //    return;
            //}
            //GetAssessedTips(detecRes);
            //if (string.IsNullOrEmpty(detecRes.Correction.Tips)
            //   || detecRes.Correction.Tips.Equals("检测合格")
            //   || detecRes.Correction.Tips.Contains("检测合格"))
            //{
            //    Log.WriteAsync("应用评价策略后图像质量检测通过");
            //    detecRes.UnAcceptItem = UnAcceptableItem.None;
            //    detecRes.Correction.Tips = "";
            //    detecRes.PassElems.PxlQcPass = true;
            //}
            //else
            //{
            //    OnDetectedNotPass(detecRes);
            //}
        }

        /// <summary>
        /// 获取评价结果
        /// </summary>
        /// <param name="detecRes">输出对象结构</param>
        protected void GetAssessedTips(RecogOut detecRes)
        {
            Action<string, string> OnDetectFailedHandler = (strInfo, errorInfo) =>
            {
                detecRes.UnAcceptItem = UnAcceptableItem.GetDetectAccess;
                _error = detecRes.Correction.Tips = strInfo + errorInfo;
                Log.WriteAsync(detecRes.Correction.Tips);
            };
            detecRes.UnAcceptItem = UnAcceptableItem.GetDetectAccess;
            string assessString = "";
            int ret = PixelDetectSDK.AssessString(_handler, out assessString); //检测检测结果评价字符串          
            if (ret != 0)
            {
                _byteImage = null;
                OnDetectFailedHandler("获取检测结果评价失败: ", DetectHandleResult.ParseErrorMessage(ret));
                Log.WriteAsync(_error);
                return;
            }
            if(assessString.Contains("不是人脸图像"))
            {
                assessString = assessString.Replace("不是人脸图像", "Face检测失败");
            }           
            detecRes.Correction.Tips = assessString;//原因  
        }

        private void OnDetectedNotPass(RecogOut detecRes)
        {
            string strLog = string.Format("质量评价结果为不通过[{0}].", detecRes.Correction.Tips);
            Log.WriteAsync(strLog);
            PhotoDirectory p = Configs.PhoDirs;
            string strErrPath = string.Format(@"{0}\{1}_{2}.jpg", p.ErrImg, DateTime.Now.ToString("yyyyMMddHHmmss"), detecRes.Correction.Tips);
            File.Copy(detecRes.DestImagePath, strErrPath, true);
            detecRes.Correction.RemainFirstError();
        }    
    }
}
